package cn.jtcoding.springframework.aop.proxy;

import cn.jtcoding.springframework.aop.aspect.AspectInfo;
import cn.jtcoding.springframework.util.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;

import java.util.List;

@Slf4j
public class CglibDynamicProxy extends AbstractDynamicProxy implements AopProxy {

    public CglibDynamicProxy(Object targetObj, List<AspectInfo> aspectInfoList) {
        super(targetObj, aspectInfoList);
    }

    @Override
    public Object getProxy() {
        return getProxy(ClassUtils.getDefaultClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        Enhancer enhancer = createEnhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(targetObj.getClass());
        enhancer.setInterfaces(targetObj.getClass().getInterfaces());
        enhancer.setClassLoader(classLoader);
        return enhancer.create();
    }

    public Enhancer createEnhancer() {
        return new Enhancer();
    }
}
